$(function () {
  window.requestAFrame = (function () {
    return window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      function (callback) {
        return window.setTimeout(callback, 1000 / 60);
      };
  })();
  window.cancelAFrame = (function () {
    return window.cancelAnimationFrame ||
      window.webkitCancelAnimationFrame ||
      window.mozCancelAnimationFrame ||
      window.oCancelAnimationFrame ||
      function (id) {
        window.clearTimeout(id);
      };
  })();
  // 
  var clipDoll = {
    data: {
      beforePrize: $(".before-prize"),
      afterPrize: $(".after-prize"),
      startBtn: $(".start-btn"),
      isLeft: true, // 轮播方向
      step: 1, // 轮播步长
      playH: 1140, // 抓子高度
      ratioH: 500, // 中途停留的高度
      playT: 600, // 时间
      num: 0, // 次数
      winIndex: null,
      touchStep: 0,
      itemWidth: 0,
      startH: 0,
      playState: null,
      carousel: null,
      lastTime: null,
      canmove: false,
      touchstart: "touchstart",
      touchmove: "touchmove",
      touchend: "touchend",
      isMobile: true
    },
    init: function () {
      var self = this.data;
      self.isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent);
      if(!self.isMobile){
        self.touchstart = "mousedown";
        self.touchmove = "mousemove";
        self.touchend = "mouseup";
      }
      self.afterPrize.html($(".before-prize").html());
      // self.afterPrize.find("").remove(); // 此处将后排奖品气泡框删除
      self.num = $(".today-nums em").text()?parseInt($(".today-nums em").text()):self.num;
      self.startH = $(".pole").height();
      self.itemWidth = parseInt(self.beforePrize.find("li").eq(0).outerWidth(true));
      self.touchStep = parseInt(self.itemWidth/self.touchStep);
      clipDoll.move();
      clipDoll.touch();
      clipDoll.play();
    },
    play: function () {
      var self = clipDoll.data;
      self.startBtn.on("click", function () {
        if(self.num > 0){
          window.cancelAFrame(self.carousel);
          self.playState = 'start';
          self.num--;
          $(".today-nums em").text(self.num--);
          clipDoll.playFrame();
        }else{
          console.log("次数已用完")
        }
      })
    },
    playFrame: function () {
      var self = clipDoll.data;
      var clip = $(".clip .footer");
      if (!self.lastTime) {
        self.lastTime = new Date();
      }
      if (self.playState == 'start') {
        // 抓子张开
        if (new Date() - self.lastTime <= 500) {
          if (clip.hasClass("move")) {
            clip.removeClass("move").addClass("put");
          } 
        } else {
          self.lastTime = new Date();
          self.playState = 'put';
        }
      }else if (self.playState == 'put') {
        // 抓子下放
        if (new Date() - self.lastTime <= self.playT+200) {
          if(!$(".pole").is(":animated")){
            $(".pole").animate({
              "height": self.startH + self.playH
            }, self.playT)
          }
        } else {
          self.lastTime = new Date();
          self.playState = 'closed';
        }
      }else if (self.playState == 'closed') {
        // 抓子合拢
        if (new Date() - self.lastTime <= 200) {
          if (clip.hasClass("put")) {
            clip.removeClass("put").addClass("closed");
          }
        } else {
          var clipL = clip.offset().left + clip.width()/2;
          var isClip = false;
          self.beforePrize.find("li").each(function () {
            var left = $(this).offset().left;
            if(left < clipL && clipL < left + $(this).width() && !$(this).hasClass("opacity")){
              self.winIndex = $(this).index();
              $(this).addClass("opacity");
              $(".prize-result").show().html($(this).find(".prize-img").prop("outerHTML"));
              isClip = true;
            }
          })
          self.lastTime = new Date();
          if (isClip) {
            self.playState = 'halfup';
          }else{
            self.playState = 'up';
          }
        }
      }else if (self.playState == 'halfup') {
        // 抓子上升
        if (new Date() - self.lastTime <= self.playT+200) {
          if(!$(".pole").is(":animated")){
            $(".pole").animate({
              "height": self.startH + self.ratioH
            }, self.playT)
          }
        } else {
          self.lastTime = new Date();
          self.playState = 'up';
        }
      }else if(self.playState == 'up'){
        // 抓子上升
        var isSuc = false;
        var resultB = parseInt($(".prize-result").css("bottom"));
        self.lastTime = null;
        self.playState = "end";
        $(".pole").animate({
          "height": self.startH
        }, self.playT)
        // 夹到的id
        console.log(self.beforePrize.find("li").eq(self.winIndex).data("id"))
        var r = Math.random();
        if (r > 0.5) { // 判断成功夹到
          $(".prize-result").animate({
            'bottom': resultB-self.playH
          }, self.playT)
        }else{
          isSuc = true;
        }
        setTimeout(function () {
          clip.removeClass("closed").addClass("move");
          self.carousel = window.requestAFrame(clipDoll.move);
          if (isSuc) {
            console.log("成功");
          }else{
            console.log("失败");
            self.beforePrize.find("li").eq(self.winIndex).removeClass("opacity");
          }
          $(".prize-result").hide().css("bottom", resultB);
        },self.playT + 100) 
      }
      if (self.playState != "end") {
        self.playTime = window.requestAFrame(clipDoll.playFrame);
      }
    },
    move: function () {
      var self = clipDoll.data;
      var beforeSlate = parseInt(self.beforePrize.css('transform').replace(/[^0-9\-,]/g,'').split(',')[4]);
      var afterSlate = parseInt(self.afterPrize.css('transform').replace(/[^0-9\-,]/g,'').split(',')[4]);
      if (self.isLeft) {
        // 左
        if (beforeSlate > -self.itemWidth) {
          beforeSlate-= self.step;
          afterSlate+= self.step;
        }else{
          // 前
          beforeLi = self.beforePrize.find("li:first").removeClass("opacity").prop("outerHTML");
          self.beforePrize.find("li:first").remove();
          self.beforePrize.append(beforeLi);
          beforeSlate = 0;
          // 后
          afterLi = self.afterPrize.find("li:last").prop("outerHTML");
          self.afterPrize.find("li:last").remove();
          self.afterPrize.find("li").eq(0).before(afterLi);
          afterSlate = 0;
        }
      } else {
        // 右
        if (beforeSlate < 0) {
          beforeSlate+=self.step;
          afterSlate-=self.step;
        } else {
          // 前
          beforeLi = self.beforePrize.find("li:last").removeClass("opacity").prop("outerHTML");
          self.beforePrize.find("li:last").remove();
          self.beforePrize.find("li").eq(0).before(beforeLi);
          beforeSlate = -self.itemWidth;
          // 后
          afterLi = self.afterPrize.find("li:first").prop("outerHTML");
          self.afterPrize.find("li:first").remove();
          self.afterPrize.append(afterLi);
          afterSlate = self.itemWidth;
        }
      }
      self.beforePrize.css({
        'transform':'translateX(' + beforeSlate +'px)',
        '-webkit-transform':'translateX(' + beforeSlate +'px)',
      });
      self.afterPrize.css({
        'transform':'translateX(' + afterSlate +'px)',
        '-webkit-transform':'translateX(' + afterSlate +'px)',
      });
      self.carousel = window.requestAFrame(clipDoll.move);
    },
    touch: function () {
      var self = clipDoll.data;
      var startX, startY, 
      slideX, slideY, 
      targetX, targetY, 
      moveX, moveY, 
      beforeSlate, afterSlate,
      beforeLi, afterLi;
      self.beforePrize.on({
        [self.touchstart]: function (e) {
          window.cancelAFrame(self.carousel);
          startX = self.isMobile?e.originalEvent.targetTouches[0].pageX:e.originalEvent.clientX;
          startY = self.isMobile?e.originalEvent.targetTouches[0].pageY:e.originalEvent.clientY;
          slideX = true;
          slideY = true;
          beforeSlate = parseInt(self.beforePrize.css('transform').replace(/[^0-9\-,]/g,'').split(',')[4]);
          afterSlate = parseInt(self.afterPrize.css('transform').replace(/[^0-9\-,]/g,'').split(',')[4]);
          self.canmove = true;
        },
        [self.touchmove]: function (e) {
          if(self.canmove){
            targetX = self.isMobile?e.originalEvent.targetTouches[0].pageX:e.originalEvent.clientX;
            targetY = self.isMobile?e.originalEvent.targetTouches[0].pageY:e.originalEvent.clientY;
            moveX = targetX - startX;
            moveY = targetY - startY;
            // 左右移动
            if (slideX && Math.abs(moveX) - Math.abs(moveY) > 0) {
              e.stopPropagation();
              if (targetX > startX) {
                // 右
                e.preventDefault();
                self.isLeft = false;
                if (beforeSlate < 0) {
                  beforeSlate+=self.touchStep?self.touchStep:parseInt(targetX - startX);
                  afterSlate-=self.touchStep?self.touchStep:parseInt(targetX - startX);
                } else {
                  // 前
                  beforeLi = self.beforePrize.find("li:last").removeClass("opacity").prop("outerHTML");
                  self.beforePrize.find("li:last").remove();
                  self.beforePrize.find("li").eq(0).before(beforeLi);
                  beforeSlate = -self.itemWidth;
                  // 后
                  afterLi = self.afterPrize.find("li:first").prop("outerHTML");
                  self.afterPrize.find("li:first").remove();
                  self.afterPrize.append(afterLi);
                  afterSlate = self.itemWidth;
                }
                startX = targetX;
              } else {
                // 左
                e.preventDefault();
                self.isLeft = true;
                if (beforeSlate > -self.itemWidth) {
                  beforeSlate-=self.touchStep?self.touchStep:parseInt(startX - targetX);
                  afterSlate+=self.touchStep?self.touchStep:parseInt(startX - targetX);
                }else{
                  // 前
                  beforeLi = self.beforePrize.find("li:first").removeClass("opacity").prop("outerHTML");
                  self.beforePrize.find("li:first").remove();
                  self.beforePrize.append(beforeLi);
                  beforeSlate = 0;
                  // 后
                  afterLi = self.afterPrize.find("li:last").prop("outerHTML");
                  self.afterPrize.find("li:last").remove();
                  self.afterPrize.find("li").eq(0).before(afterLi);
                  afterSlate = 0;
                }
                startX = targetX;
              }
              window.requestAFrame(function () {
                self.beforePrize.css({
                  'transform':'translateX(' + beforeSlate +'px)',
                  '-webkit-transform':'translateX(' + beforeSlate +'px)'
                });
                self.afterPrize.css({
                  'transform':'translateX(' + afterSlate +'px)',
                  '-webkit-transform':'translateX(' + afterSlate +'px)',
                })
              })
              slideY = false;
            }
            // 上下滑动
            if (slideY && Math.abs(moveX) - Math.abs(moveY) < 0) {
              slideX = false;
            }
          }
        },
        [self.touchend]: function () {
          self.canmove = false;
          self.carousel = window.requestAFrame(clipDoll.move);
        },
        "mouseout": function () {
          window.cancelAFrame(self.carousel);
          self.carousel = window.requestAFrame(clipDoll.move);
          self.canmove = false;
        }
      })
    }
  }
  clipDoll.init();
})